package ink.xiaobaibai.handler;

import ink.xiaobaibai.token.JWTAuthenticationToken;
import ink.xiaobaibai.units.JWTUnit;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description: JWT验证成功处理器
 * @author: 小白白
 * @create: 2021-05-14
 **/

public class JWTSuccessHandler implements AuthenticationSuccessHandler {

    /**
     * 检验成功,检验是否需要更新jwt
     *
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if (!(authentication instanceof JWTAuthenticationToken)) {
            return;
        }
        String newJwt = JWTUnit.updateJWT(((JWTAuthenticationToken) authentication).getUserId());
        if (newJwt != null) {
            //不为空说明需要更新
            response.setHeader("Authorization", newJwt);
        }
    }

}
